<script setup lang="ts">
import { ElRow, ElCol, ElCard, ElSkeleton, ElDatePicker, ElButton } from 'element-plus'
import { Icon } from '@/components/Icon'
import { CountTo } from '@/components/CountTo'
import { useDesign } from '@/hooks/web/useDesign'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive, computed } from 'vue'
import { set } from 'lodash-es'
import { getCountApi } from '@/api/dashboard/analysis'
import type { AnalysisTotalTypes } from '@/api/dashboard/analysis/types'
import { EChartsOption } from 'echarts'
import { lineOptions } from '../echarts-data'
import { postDay15Api } from '@/api/dashboard/analysis'
import dayjs from 'dayjs'

const { t } = useI18n()

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('panel')

const loading = ref(true)

// 默认日期范围：当天往前1个月
const defaultDateRange = [
  dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
  dayjs().format('YYYY-MM-DD')
]

const selectedDateRange = ref<string[]>(defaultDateRange)
const selectedYear = ref(new Date().getFullYear())

// 计算日期范围
const computedDateRange = computed(() => {
  if (selectedDateRange.value && selectedDateRange.value.length === 2) {
    const startDate = dayjs(selectedDateRange.value[0])
    const endDate = dayjs(selectedDateRange.value[1])
    return {
      start: startDate.format('YYYY/MM/DD'),
      end: endDate.format('YYYY/MM/DD'),
      display: `${startDate.format('YYYY/MM/DD')}-${endDate.format('YYYY/MM/DD')}`
    }
  }
  return {
    start: '',
    end: '',
    display: ''
  }
})

// 定义 emit
const emit = defineEmits<{
  filter: []
}>()

// Filter handler
const handleFilter = async () => {
  console.log('Filter clicked with date range:', selectedDateRange.value)
  loading.value = true
  
  // 获取开始日期和结束日期
  // fromDay 是开始日期，yearOrDay 是结束日期
  const fromDay = selectedDateRange.value && selectedDateRange.value[0] 
    ? selectedDateRange.value[0] 
    : defaultDateRange[0]
  const yearOrDay = selectedDateRange.value && selectedDateRange.value[1] 
    ? selectedDateRange.value[1] 
    : defaultDateRange[1]
  
  await Promise.all([getCount(yearOrDay, fromDay, false), getDay15Api()])
  loading.value = false
  // 触发父组件的筛选事件
  emit('filter')
}

// Reset handler
const handleReset = async () => {
  selectedDateRange.value = [...defaultDateRange]
  selectedYear.value = new Date().getFullYear()
  loading.value = true
  await Promise.all([getCount(undefined, undefined, false), getDay15Api()])
  loading.value = false
  // 触发父组件的筛选事件
  emit('filter')
}
const lineData = reactive<EChartsOption>(lineOptions) as EChartsOption
// 数据总表
const data = reactive({
  items: []
})

const getDay15Api = async () => {
  try {
    // fromDay 是开始日期，yearOrDay 是结束日期
    const fromDay = selectedDateRange.value && selectedDateRange.value[0] 
      ? selectedDateRange.value[0] 
      : defaultDateRange[0]
    const yearOrDay = selectedDateRange.value && selectedDateRange.value[1] 
      ? selectedDateRange.value[1] 
      : defaultDateRange[1]
    const res = await postDay15Api({
      yearOrDay,
      fromDay
    })
    if (res && res.data && res.data.items) {
      data.items = res.data.items
      set(
        lineData,
        'xAxis.data',
        res.data.items.map((v) => v.day)
      )
      set(lineData, 'series', [
        {
          name: t('analysis.income'),
          smooth: true,
          type: 'line',
          data: res.data.items.map((v) => v.income),
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        },
        {
          name: t('analysis.expenditure'),
          smooth: true,
          type: 'line',
          itemStyle: {
            color: '#ff0000'
          },
          data: res.data.items.map((v) => v.expenditure),
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        },
        {
          name: t('analysis.profit'),
          smooth: true,
          type: 'line',
          itemStyle: {},
          data: res.data.items.map((v) => v.profit),
          animationDuration: 2800,
          animationEasing: 'quadraticOut'
        }
      ])
    }
  } catch (error) {
    console.error('Error fetching day15 data:', error)
  }
}

let totalState = reactive<AnalysisTotalTypes>({
  income: 0,
  grpNum: 0,
  accNum: 0,
  expenditure: 0,
  profit:0
})

const getCount = async (yearOrDay?: string, fromDay?: string, setLoading = true) => {
  // 如果没有传参数，默认使用当前时间框的日期范围（一个月）
  // fromDay 是开始日期，yearOrDay 是结束日期
  const finalFromDay = fromDay || (selectedDateRange.value && selectedDateRange.value[0] ? selectedDateRange.value[0] : defaultDateRange[0])
  const finalYearOrDay = yearOrDay || (selectedDateRange.value && selectedDateRange.value[1] ? selectedDateRange.value[1] : defaultDateRange[1])
  const data = { yearOrDay: finalYearOrDay, fromDay: finalFromDay }
  const res = await getCountApi(data)
    .catch(() => {})
    .finally(() => {
      if (setLoading) {
        loading.value = false
      }
    })
  totalState = Object.assign(totalState, res?.data || {})
}

// 监听年份选择变化 - 已移除自动触发，改为只在点击筛选按钮时触发
// watch(selectedYear, (newYear) => {
//   loading.value = true
//   getCount(newYear)
// })

getCount()

const getAllApi = async () => {
  try {
    await Promise.all([getDay15Api()])
  } catch (error) {
    console.error('Error fetching data:', error)
  } finally {
    loading.value = false
  }
}
getAllApi()

// 暴露数据供父组件使用
defineExpose({
  computedDateRange,
  selectedDateRange
})
</script>

<template>
  <div class="panel-header">
    <h2 class="panel-title">总数据面板</h2>
    <div class="filter-controls">
      <div class="filter-date-input">
        <ElDatePicker
          v-model="selectedDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </div>
      <ElButton type="primary" size="small" class="filter-btn" @click="handleFilter">
        筛选
      </ElButton>
      <ElButton size="small" plain class="reset-btn" @click="handleReset">
        重置
      </ElButton>
    </div>
  </div>
  <ElRow :gutter="0" :class="prefixCls">
    <ElCol :xl="4" :lg="4" :md="8" :sm="12" :xs="24" class="panel-col">
      <ElCard shadow="never">
        <ElSkeleton :loading="loading" animated :rows="3">
          <template #default>
            <div :class="`${prefixCls}__item panel-content-1`">
              <div class="panel-title-row">
                <div class="panel-icon">
                  <Icon icon="vi-ep:wallet-filled" :size="32" color="#409eff" />
                </div>
                <div class="panel-title-text">{{
                  t('analysis.airdropAllYield')
                }}</div>
              </div>
              <div class="panel-value-row">
                <div class="panel-value">$<CountTo
                  class="value-number"
                  :start-val="0"
                  :end-val="totalState.income"
                  :duration="2600"
                /></div>
                <div class="panel-unit">{{ t('analysis.usdt') }}</div>
              </div>
            </div>
          </template>
        </ElSkeleton>
      </ElCard>
    </ElCol>

    <ElCol :xl="4" :lg="4" :md="8" :sm="12" :xs="12" class="panel-col">
      <ElCard shadow="never">
        <ElSkeleton :loading="loading" animated :rows="2">
          <template #default>
            <div :class="`${prefixCls}__item panel-content-simple`">
              <div class="panel-title-text">{{ t('analysis.groupTotal') }}</div>
              <CountTo
                class="panel-value-number"
                :start-val="0"
                :end-val="totalState.grpNum"
                :duration="2600"
              />
            </div>
          </template>
        </ElSkeleton>
      </ElCard>
    </ElCol>

    <ElCol :xl="4" :lg="4" :md="8" :sm="12" :xs="12" class="panel-col">
      <ElCard shadow="never">
        <ElSkeleton :loading="loading" animated :rows="2">
          <template #default>
            <div :class="`${prefixCls}__item panel-content-simple`">
              <div class="panel-title-text">{{ t('analysis.binanceAuccountTotal') }}</div>
              <CountTo
                class="panel-value-number"
                :start-val="0"
                :end-val="totalState.accNum"
                :duration="2600"
              />
            </div>
          </template>
        </ElSkeleton>
      </ElCard>
    </ElCol>

    
    <ElCol :xl="4" :lg="4" :md="8" :sm="12" :xs="12" class="panel-col">
      <ElCard shadow="never">
        <ElSkeleton :loading="loading" animated :rows="2">
          <template #default>
            <div :class="`${prefixCls}__item panel-content-money`">
              <div class="panel-title-text">{{ t('analysis.netprofitTotal') }}</div>
              <div class="panel-value">$<CountTo
                class="value-number"
                :start-val="0"
                :end-val="totalState.profit"
                :duration="2600"
              /></div>
            </div>
          </template>
        </ElSkeleton>
      </ElCard>
    </ElCol>
    <ElCol :xl="4" :lg="4" :md="8" :sm="12" :xs="12" class="panel-col">
      <ElCard shadow="never">
        <ElSkeleton :loading="loading" animated :rows="2">
          <template #default>
            <div :class="`${prefixCls}__item panel-content-money`">
              <div class="panel-title-text">{{ t('analysis.depletionTotal') }}</div>
              <div class="panel-value">$<CountTo
                class="value-number"
                :start-val="0"
                :end-val="totalState.expenditure"
                :duration="2600"
              /></div>
            </div>
          </template>
        </ElSkeleton>
      </ElCard>
    </ElCol>


    
  </ElRow>
</template>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}

// Panel header styles
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  // 手机端响应式：标题在第一行左侧，筛选控件在第二行
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 16px;
    padding: 0 12px;
  }
}

.panel-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  margin-left: 20px;
  
  // 手机端样式：第一行左侧
  @media (max-width: 768px) {
    font-size: 28px;
    font-weight: 600;
    margin-left: 0;
    margin-top: 10px;
    flex-shrink: 0;
    white-space: nowrap;
    width: 100%;
  }
}

// Filter section styles
.filter-controls {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 8px;
  
  // 手机端响应式：第二行，日期选择器在左，按钮在右
  @media (max-width: 768px) {
    width: 100%;
    justify-content: space-between;
    flex-wrap: nowrap;
    gap: 8px;
    margin-left: 0;
    align-items: center;
  }
}

.filter-date-input {
  :deep(.el-input__wrapper) {
    border-color: #a3d4ff;
    background-color: #f0f8ff;
    box-shadow: 0 0 0 1px #a3d4ff inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #409eff inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
      background-color: #fff;
    }
  }
  
  :deep(.el-input__prefix) {
    .el-icon {
      color: #808080;
    }
  }
  
  :deep(.el-input__inner) {
    color: #606266;
  }
  
  // 手机端响应式：在第二行左侧，与按钮并排
  @media (max-width: 768px) {
    flex: 1;
    min-width: 0;
    max-width: none;
    margin-bottom: 0;
    
    :deep(.el-input__wrapper) {
      padding: 4px 8px;
      height: 28px;
      
      .el-input__inner {
        font-size: 12px;
        padding: 0 4px;
      }
      
      .el-input__prefix {
        padding: 0 4px;
      }
    }
    
    :deep(.el-date-editor) {
      width: 100%;
    }
  }
}

.filter-btn {
  border-radius: 6px;
  padding: 8px 20px;
  
  // 手机端响应式：按钮更小更紧凑，保持在第二行
  @media (max-width: 768px) {
    padding: 5px 12px;
    font-size: 12px;
    flex-shrink: 0;
    flex-grow: 0;
    height: 28px;
    border-radius: 4px;
  }
}

.reset-btn {
  border-radius: 6px;
  border-color: #dcdfe6;
  
  &:hover {
    color: #409eff;
    border-color: #409eff;
  }
  
  // 手机端响应式：按钮更小更紧凑，保持在第二行
  @media (max-width: 768px) {
    padding: 5px 12px;
    font-size: 12px;
    flex-shrink: 0;
    flex-grow: 0;
    height: 28px;
    border-radius: 4px;
    
    .mr-1 {
      font-size: 12px;
      margin-right: 4px;
    }
  }
}

@prefix-cls: ~'@{adminNamespace}-panel';

.@{prefix-cls} {
  margin: 0 !important;
}

.panel-col {
  padding: 0 !important;
  
  :deep(.el-card) {
    height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    box-shadow: none;
    border: none;
    border-radius: 0;
    background-color: #fff;
    margin: 0;
  }
  
  :deep(.el-card__body) {
    padding: 16px 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  @media (min-width: 1200px) {
    flex: 0 0 20%;
    max-width: 20%;
  }
  @media (min-width: 992px) and (max-width: 1199px) {
    flex: 0 0 20%;
    max-width: 20%;
  }
  
  // 手机端样式调整
  @media (max-width: 575px) {
    .mb-20px {
      margin-bottom: 8px !important;
    }
  }
}

.@{prefix-cls} {
  &__item {
    height: 100%;
    
    &.panel-content-1 {
      display: flex;
      flex-direction: column;
      
      .panel-title-row {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
      }
      
      .panel-icon {
        margin-right: 8px;
      }
      
      .panel-title-text {
        font-size: 14px;
        color: #909399;
      }
      
      .panel-value-row {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
      }
      
      .panel-value {
        font-size: 28px;
        font-weight: 700;
        color: #303133;
      }
      
      .panel-unit {
        font-size: 12px;
        color: #909399;
      }
    }
    
    &.panel-content-simple {
      display: flex;
      flex-direction: column;
      justify-content: center;
      
      .panel-title-text {
        font-size: 14px;
        color: #909399;
        margin-bottom: 12px;
        text-align: center;
        
        // 手机端响应式：左对齐
        @media (max-width: 575px) {
          text-align: left;
        }
      }
      
      .panel-value-number {
        font-size: 26px;
        font-weight: 700;
        color: #303133;
        text-align: center;
        
        // 手机端响应式：左对齐
        @media (max-width: 575px) {
          text-align: left;
        }
      }
    }
    
    &.panel-content-money {
      display: flex;
      flex-direction: column;
      justify-content: center;
      
      .panel-title-text {
        font-size: 14px;
        color: #909399;
        margin-bottom: 12px;
      }
      
      .panel-value {
        font-size: 28px;
        font-weight: 700;
        color: #303133;
      }
    }
  }
}
</style>
